<?php




/**
* tags Class
*/

class tags
extends entity
{
	/**
	* Optional Constructor: Load on demand only.
	*/
	public function __construct()
	{
		# Parent's default constructor is necessary.
		parent::__construct();

		/**
		* Set Private, Protected or Public Members
		*/
		$this->protection_code = 'a01521773e39f3a39b0c649d1ad02658'; # Some random text, valid for the entire life
		$this->table_name = 'gallery_tags'; # Name of this table/entity name
		$this->pk_column = 'tag_id'; # Primary Key's Column Name

		/**
		* Validation fields as used in add/edit forms
		*/
		$this->fields = array(
			# Remove the columns that you do not want to use in the ADD form
			'add' => array(
				'tag_name' => null,
				'tag_plural' => null,
				'tag_singular' => null,
				'tag_icon' => null,
			),
			
			# Remove the columns that you do not want to use in the EDIT form
			'edit' => array(
				'tag_name' => null,
				'tag_plural' => null,
				'tag_singular' => null,
				'tag_icon' => null,
			),
		);
	}

	/**
	* List entries from [ tags ]
	* Column `code` signifies a protection code while deleting/editing a record
	* @param $conditions SQL Conditions
	* @return Multi-Dimensional array of entries in the list
	*/
	public function list_entries(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ tags ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`{$this->pk_column}`, # Do not remove this
	
	# Modify these columns to your own required list (e.*)
	e.`tag_name`,
	e.`tag_plural`,
	e.`tag_singular`,
	e.`tag_icon`,
	
	# Flags, load them as per your need
	e.`is_approved`,
	e.images_counter,
	e.search_counter,
	
	MD5(CONCAT(e.`{$this->pk_column}`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_tags` `e`
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	#e.`sink_weight` ASC,
	#e.`{$this->pk_column}` DESC
	e.tag_name
LIMIT {$from_index}, {$per_page}
;";
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = isset($totals['total'])?$totals['total']:0;

		return $entries;
	}
	
	/**
	* Details of an entity in [ tags ] for management activities only.
	* @param $pk integer Primary Key's value of an entity
	* @return $details Associative Array of Detailed records of an entity
	*/
	public function details($tag_id=0)
	{
		global $subdomain_id;
		
		$tag_id = (int)$tag_id;
		$details_sql="
SELECT
	e.`{$this->pk_column}`, # Do not remove this

	e.*, # Modify these columns,
	
	# Admin must have it to EDIT the records
	MD5(CONCAT(e.`{$this->pk_column}`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_tags` `e`
WHERE
	e.`{$this->pk_column}` = {$tag_id}
	AND e.is_active='Y'
	# AND e.subdomain_id={$subdomain_id}
;";
		$details = $this->row($details_sql);
		return $details;
	}

	/**
	* Details of an entity in [ tags ] for public display.
	* @param $pk integer Primary Key's value of an entity
	* @return $details Associative Array of Detailed records of an entity
	*/
	public function get_details($tag_id=0, $protection_code='')
	{
		$tag_id = (int)$tag_id;
		$protection_code = $this->sanitize($protection_code);
		$details_sql="
SELECT
	e.`{$this->pk_column}`, # Do not remove this

	e.*, # Modify these columns

	MD5(CONCAT(e.`{$this->pk_column}`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_tags` `e`
WHERE
	e.`{$this->pk_column}` = {$tag_id}
	AND e.is_active='Y'

	# Optionally validate
	AND MD5(CONCAT(e.`{$this->pk_column}`, '{$this->protection_code}')) = '{$protection_code}'
;";
		$details = $this->row($details_sql);
		return $details;
	}

	/**
	* Flag a field; dummy use; unless you use it.
	* Every method should sanitize the user input.
	* It will co-exist with the live features.
	*/
	public function flag_field($tag_id=0, $protection_code='', $field_name='')
	{
		# Allow only selected fields to be flaged Y/N
		if(!in_array($field_name, array('is_approved', 'is_featured')))
		{
			# Such flag does not exist.
			return false;
		}
		
		$tag_id = (int)$tag_id;
		$protection_code = $this->sanitize($protection_code);
		global $subdomain_id;

		$flag_sql="
UPDATE `gallery_tags` SET
	# Set your flag name here
	`{$field_name}`=IF(`{$field_name}`='Y', 'N', 'Y')
WHERE
	`{$this->pk_column}` = {$tag_id}
	#AND subdomain_id={$subdomain_id}
	
	# Don't touch the deleted flags
	AND is_active='Y'

	# Optionally validate
	AND MD5(CONCAT(`{$this->pk_column}`, '{$this->protection_code}')) = '{$protection_code}'
;";
		return $this->query($flag_sql);
		#return false; # dummy mode only
	}

	/**
	* Welcome and ask for authentication?
	* Please extend this method according to your business logic.
	* eg. Send email to the first signed up member, trigger something else when a data is added.
	* Called right after a new [ tags ] is added: insert-hook.
	*/
	public function welcome_first($tag_id=0)
	{
		$tag_id = (int)$tag_id;
	 	
		return true;
	}
	
	/**
	* Modify the image tags while editing or adding new.
	*/
	public function correct_image_tags($image_id=0, $tags='')
	{
		# Delete all existing tags first.
		$image_id = (int)$image_id;
		$delete_tags_sql = "DELETE FROM gallery_images_tags WHERE image_id={$image_id}";
		$this->query($delete_tags_sql);
		
		$tags_words = preg_split('/[,|;]+/', $tags);
		$tags_words = array_map('trim', $tags_words);
		$tags_words = array_unique($tags_words);
		foreach($tags_words as $t => $tag_word)
		{
			$tag_id = $this->tag_id($tag_word, true);
			#echo "\r\n<br>{$tag_id} : {$tag_word}";
			
			# Add the tag
			$tag_add_sql="INSERT INTO gallery_images_tags (image_id, tag_id, is_active, is_approved) VALUES ({$image_id}, {$tag_id}, 'Y', 'Y');";
			$this->query($tag_add_sql);
		}
		#print_r($tags_words);
		$image_id = (int)$image_id;
		#echo $tags;
	}
	
	/**
	* Modify the category tags while editing or adding category
	* @todo Helps in finding the related items.
	*/
	public function correct_category_tags($category_id=0, $tags='')
	{
		# Delete all existing tags first.
		$category_id = (int)$category_id;
		$delete_tags_sql = "DELETE FROM gallery_category_tags WHERE category_id={$category_id}";
		$this->query($delete_tags_sql);
		
		$tags_words = preg_split('/[,|;]+/', $tags);
		$tags_words = array_map('trim', $tags_words);
		$tags_words = array_unique($tags_words);
		foreach($tags_words as $t => $tag_word)
		{
			$tag_id = $this->tag_id($tag_word, true);
			
			# Add the tag
			$tag_add_sql="INSERT INTO gallery_category_tags (category_id, tag_id) VALUES ({$category_id}, {$tag_id});";
			$this->query($tag_add_sql);
		}
		$category_id = (int)$category_id;
	}
	
	/**
	* Add or read tag ID
	*/
	private function tag_id($tag_word='', $attempt_to_add=false)
	{
		global $subdomain_id;
		if($attempt_to_add==true)
		{
			$add_tag = "INSERT IGNORE INTO gallery_tags (subdomain_id, is_active, is_approved, tag_name) VALUES ({$subdomain_id}, 'Y', 'Y', '{$tag_word}');";
			$this->query($add_tag);
		}
		
		$tag_sql="SELECT tag_id FROM gallery_tags WHERE tag_name='{$tag_word}';";
		$tag = $this->row($tag_sql);
		if(!isset($tag['tag_id'])) $tag = array('tag_id' => 0);
		
		return $tag['tag_id'];
	}
	
	/**
	* Keep a search log of keywords
	*/
	public function search_log($search_term='')
	{
		global $subdomain_id;
		$search_term = addslashes($search_term);
		$search_log_sql="
INSERT INTO gallery_tags (
	subdomain_id, added_on, is_active, is_approved, is_searched,
	tag_name
) VALUES (
	{$subdomain_id}, UNIX_TIMESTAMP(), 'Y', 'N', 'Y',
	'{$search_term}'
) ON DUPLICATE KEY UPDATE
	search_counter=search_counter+1,
	search_on = UNIX_TIMESTAMP()
;";
		#die($search_log_sql);
		return $this->query($search_log_sql);
	}
}
?>